<template>
    <el-transfer
        :titles="['所有商品', '已选中商品']"
        :button-texts="['移除', '添加']"
        :data="goods"
        :props="{
            key: 'id',
            label: 'name'
        }"
        v-model="goodsId"
        @change="handleChange"
    >
    </el-transfer>
    <el-button type="primary" plain style="margin-top: 20px;" @click="upload()">确定</el-button>
</template>

<script setup>
import { ref } from 'vue'
import { get, post } from '@/plugins/axios'
import { ElMessage } from 'element-plus';
import url from './pathUtil'
const  emits = defineEmits(['update:show'])
const props = defineProps(['marketingId'])
let goods = ref([])
const goodsId = ref([])
const maxSelected = 5 // 最大选择数量
getTableData()
function getTableData() {
    get('/goods/getList', {}, content => {
        goods.value = content
        console.log(content)
	})
}
getById()
function getById() {
    get(url.getById, { id: props.marketingId }, content => {
        goodsId.value = content.goodsId
        console.log(goodsId.value)
    })
}
function handleChange(value, direction, movedKeys) {
    // 检查已选数量是否超过最大限制
    if (value.length > maxSelected) {
        
        // 如果超过，则不允许添加更多，并提示用户
        ElMessage({
            type: 'error',
            message: '最多可选择5个'
        })
        // 从已选列表中移除超出的选项
        if (direction === 'right') {
            for (let i = goodsId.value.length; i > 4; i--) {
                goodsId.value.splice(i, 1)
            }
        }
      } else {
        // 如果未超过，则更新selectedKeys
        goodsId.value = value;
      }
}
function upload() {
    console.log(goodsId)
    // let id = new Array()
    // for (let i = 0; i < goodsId.length; i++) {
    //     id.push(goodsId.value[i])
    // }
    // console.log(id)
    post(url.addGoods, { marketingId: props.marketingId, goodsId: goodsId.value }, content => {
        getTableData()
        emits('update:show', false)
    })
}
</script>

<style scoped>
</style>